import { DialogService } from 'ng-devui/modal';

import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { CheckableRelation, DataTableComponent, TableWidthConfig } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { AssignUserComponent } from 'src/app/@shared/components/assign-user/assign-user.component';

@Component({
  selector: 'app-product-dispatch-list',
  templateUrl: './product-dispatch-list.component.html',
  styleUrls: ['./product-dispatch-list.component.scss'],

})
export class ProductDispatchListComponent {
  msgs: Array<Object> = [];
  rangeDate=[

  ];
  assginData:any={
    jobOrderList: [
      {
        jobOrderId: 0,
        employeeCodes: [],
        processId: 0,
        jobNum: '',
        processName: '',
        processNumber: 0
      }
    ],
    employeeIds: [
      ''
    ]
  }
  checkRows:any[]=[];
  stateOptions=[
   '未核准','核准未派工','派工未完工','完工未完结','已完结'
  ]
  tableData:any[]=[
    {}
  ]
  dataTableOptions={
    columns:[
      {
          field: 'name',
          header: '工序序号',
          fieldType: 'text',
          fixedLeft: '250px'
      },
      {
        field: 'name',
        header: '工序编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '工单名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '状态',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '人员',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '完成进度',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '报工数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '生产模式',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '首检',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '末检',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '计划开始时间',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '实际开始时间',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '计划结束时间',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '实际结束时间',
        fieldType: 'text',
      },

    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field:'操作',
      width:'250px'
    },
    {
      field:'工单号',
      width:'250px'
    },
    {
      field:'销售订单号',
      width:'250px'
    },
    {
      field:'销售订单号',
      width:'250px'
    },
    {
      field:'产品编码',
      width:'150px'
    },
    {
      field:'产品名称',
      width:'150px'
    },
    {
      field:'规格',
      width:'150px'
    },
    {
      field:'单位',
      width:'150px'
    },
    {
      field:'计划数量',
      width:'150px'
    },
    {
      field:'已入库数量',
      width:'150px'
    },
    {
      field:'进度',
      width:'150px'
    },
    {
      field:'PlanStartTime',
      width:'150px'
    },
    {
      field:'ActualStartTime',
      width:'150px'
    },
    {
      field:'PlanEndTime',
      width:'150px'
    },
    {
      field:'ActualEndTime',
      width:'150px'
    },

  ];
  checkedIds = [];
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  optionsStatus = [
    "未核准",
    "已核准",
    "未派工",
    "未完工",
    "未完结",
    "已完结"
  ]
  pageSizeOptions = [10, 20, 30, 50, 100];
  partNum: string = null;
  partName: string = null;
  JobOrderNum: string = null;
  JobOrderStatus: string = null;
  JobOrderType: string = null;
  StartDate: string = null;
  EndDate: string = null;
  jobOrderProcesses:any[]=[];
  productJob=[]
  revokeAssignData=[
    {
      jobOrderId: 0,
      employeeCodes: [
        ""
      ],
      userName: [
        ""
      ],
      processId: 0,
      jobNum: "",
      processName: "",
      processNumber: 0
    }
  ];
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  isIconRotated = false;
  constructor(private SharedMethodService:SharedMethodService,private JobOrderService:JobOrderService,private Router:Router,private DialogService:DialogService) { }
  ngOnInit(): void {
    this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData=data.items
      this.tableData.forEach(item => {
        item.display = false;
      });


      this.pager.total=data.totalCount;
    })
  }
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
  }//切换页码
  pageSizeChange($event: any){

  }//改变每页显示数量
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  rangeDateChange(event:any){
    this.rangeDate = event;
    this.StartDate = this.rangeDate[0].toISOString().split('T')[0]
    this.EndDate = this.rangeDate[1].toISOString().split('T')[0]

  }//日期范围选择
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.tableData,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: any) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable);
    for (let item of rowItem.jobOrderProcesses) {
      item.$checked = rowItem.$checked;
    }
  }//单选
  onChildRowCheckChange(checked: boolean, rowIndex: number, nestedIndex: any, rowItem: any, item: any) {
    item.$checked = checked;
    rowItem.$checked = rowItem.jobOrderProcesses.every((item: any) => item.$checked);
    rowItem.$halfChecked = rowItem.jobOrderProcesses.some((item: any) => item.$checked) && !rowItem.$checked;


  }//子单选
  getCheckedRows() {
      if(this.datatable._pageAllChecked || this.datatable.halfChecked){
        const rows = this.datatable.getCheckedRows();

        const checkRows = rows.filter((item: any) => item.$checked);
        checkRows.forEach((item: any) => {
        item.jobOrderProcesses.forEach((process: any) => {
          process.$checked = item.$checked;
          });
        });
        this.checkRows = checkRows.map((item: any) => {
          item.jobOrderProcesses = item.jobOrderProcesses.map((process: any) => {
            return {
              ...process,
              jobNum: item.jobNum // 添加新的属性 jobNum
            };
          });
          return item.jobOrderProcesses
        }).flat();
      }else{
        const rows = this.datatable._dataSource;
        rows.forEach((item: any) => {
        item.jobOrderProcesses.forEach((process: any) => {
          process.$checked = false
          });
        });
      }


  }//获取选中行
  getChildCheckedRows(rowItem:any) {
    const checkRows = rowItem.jobOrderProcesses
    .filter((item: any) => item.$checked)
    .map((item: any) => {
      return {
        ...item,
        jobNum: rowItem.jobNum // 添加新的属性 jobNum
      };
    });
    this.checkRows = checkRows;

  }//获取选中行
  search(){
    this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData=data.items
      this.pager.total=data.totalCount;
    })
  }
  reset(){
    this.partNum=null;
    this.partName=null;
    this.JobOrderNum=null;
    this.JobOrderStatus=null;
    this.JobOrderType=null;
    this.StartDate=null;
    this.EndDate=null;
    this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData=data.items
      this.pager.total=data.totalCount;
    })
  }
  viewJob(id:any){
    this.Router.navigate(['/pages/product/job-detail/',id])
  }
  EditJob(id:any){
    this.Router.navigate(['/pages/product/edit-product-job/',id])
  }
  delete(id:any){
    this.JobOrderService.DeleteJobOrders([id]).subscribe((data:any)=>{
      this.showToast('success','成功','删除成功')
      this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData=data.items
        this.pager.total=data.totalCount;
      })
    },error=>{
      this.showToast('error','失败',error.error.message)
    })
  }
  deletes(){
    this.JobOrderService.DeleteJobOrders(this.checkedIds).subscribe((data:any)=>{
      this.showToast('success','成功','删除成功')
      this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData=data.items
        this.pager.total=data.totalCount;
      })
    },error=>{
      this.showToast('error','失败',error.error.message)
    })
  }
  Approval(id:any){
    this.JobOrderService.ApprovalJobOrder(id).subscribe((data:any)=>{
      this.showToast('success','核准成功','核准成功')
      this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData=data.items
        this.pager.total=data.totalCount;
      })
    },error=>{
      this.showToast('error','核准失败',error.error.message)
    })
  }
  unApproval(id:any){
    this.JobOrderService.UnApprovalJobOrder(id).subscribe((data:any)=>{
      this.showToast('success','取消核准成功','取消核准成功')
      this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData=data.items
        this.pager.total=data.totalCount;
      })
    },error=>{
      this.showToast('error','取消核准失败',error.error.message)
    })
  }
  loadChildrenTable = (rowItem: any) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(rowItem.jobOrderProcesses);
      }, 500);
    });
  }
  onChildTableToggle(status: any, rowItem: any) {
    this.datatable.setRowChildToggleStatus(rowItem, status);
  }
  toggleRowItem(rowItem: any,rowIndex: number) {
    rowItem.display = !rowItem.display;
  }
  dispatch(rowItem?:any,dialogtype?:string,){
    const results = this.DialogService.open({
      title: '分配人员',
      data:{
        data:[rowItem],
        title:'派工'
      },
      content: AssignUserComponent,
      dialogtype: dialogtype,
      width:'1000px',
      draggable:false,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.JobOrderService.GetJobOrders(this.partNum,this.partName,this.JobOrderNum,this.JobOrderStatus,this.JobOrderType,null,this.StartDate,this.EndDate,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
              this.tableData=data.items
              this.pager.total=data.totalCount;
              this.checkedIds = []
            },error=>{
              this.showToast('danger','错误',error.error.message)
            }
          )
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  revokeAssign( rowItem:any,dialogtype?: string,) {
    console.log(rowItem)
    const data  = [{
      jobOrderProcessID:rowItem.jobOrderProcessId
    }]
    const results = this.DialogService.open({
      title: '分配人员',
      data: {
        title: '撤回'
      },
      content: '是否全部撤回？',
      dialogtype: dialogtype,
      width: '400px',

      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
              this.JobOrderService.RevokeAssignProcessesToUser(data).subscribe((data: any) => {
                this.showToast('success', '成功', '撤回成功')
                this.search()
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              })

            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getUserNames(item:any): string {
    return item.users.map((a: any) => a.name).join('，');
  }

  // ================= 打印：派工 =================
  // 从顶部按钮打印：要求仅选择一条工单（rowItem.display结构下的父项）
  printCurrentOrder(): void {
    // 顶部列表是父行，不使用复选框，这里只允许可视区域里第一个展开的为打印对象，或提示用户点击某一行右侧“打印”
    const expanded = (this.tableData || []).find((x: any) => x && x.display === true);
    if (!expanded) {
      this.showToast('warning', '提示', '请展开一个工单或使用行内“打印”');
      return;
    }
    const html = this.buildJobProcessPrintHtml(expanded);
    this.printWithIframe(html);
  }

  // 行内打印：传入父行row和子项process，若仅传row则打印整单，传process则仅打印该工序块
  printProcess(rowItem: any, process?: any): void {
    if (!rowItem) {
      this.showToast('warning', '提示', '未找到可打印的工单数据');
      return;
    }
    const order = process ? { ...rowItem, jobOrderProcesses: [process] } : rowItem;
    const html = this.buildJobProcessPrintHtml(order);
    this.printWithIframe(html);
  }

  private printWithIframe(html: string) {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document as Document | undefined;
    if (!doc) {
      document.body.removeChild(iframe);
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          if (iframe && iframe.parentNode) {
            iframe.parentNode.removeChild(iframe);
          }
        }, 400);
      }
    }, 200);
  }

  private to2(n: any): string {
    const x = Number(n);
    if (isNaN(x)) return '';
    return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  private fmtDateStr(input: any, withTime = false): string {
    if (!input) return '';
    const d = new Date(input);
    if (isNaN(d.getTime())) return String(input);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const da = String(d.getDate()).padStart(2, '0');
    if (!withTime) return `${y}-${m}-${da}`;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${da} ${hh}:${mm}`;
  }

  private buildJobProcessPrintHtml(order: any): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px 12px; margin-top: 8px; }
        .grid .cell { font-size: 12px; }
        .remark { margin-top: 10px; white-space: pre-wrap; }
        .footer { margin-top: 24px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
        .footer .cell { font-size: 12px; color: #555; }
        .sub-title { margin-top: 14px; font-weight: 700; font-size: 14px; }
        .muted { color: #666; }
        .process-block { margin-top: 8px; border: 1px solid #333; padding: 4px 6px; }
        .process-head { font-size: 12px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px 8px; }
        .process-head .item { white-space: normal; overflow: visible; text-overflow: initial; }
        .subtable th, .subtable td { font-size: 11px; }
      </style>
    `;

    const safe = (v: any) => v ?? '';
    const title = '派工单';
    const headTable = `
      <table>
        <colgroup>
          <col style="width: 15%"/><col style="width: 35%"/>
          <col style="width: 15%"/><col style="width: 35%"/>
        </colgroup>
        <tbody>
          <tr><th>工单号</th><td>${safe(order?.jobNum)}</td><th>产品编号</th><td>${safe(order?.productNum)}</td></tr>
          <tr><th>产品名称</th><td>${safe(order?.productName)}</td><th>规格型号</th><td>${safe(order?.partType)}</td></tr>
          <tr><th>计划数量</th><td>${safe(order?.productionQuantity)}</td><th>已入库数量</th><td>${safe(order?.receivedQuantity)}</td></tr>
          <tr><th>计划开始</th><td>${safe(order?.jobOrderPlanStartDate)}</td><th>计划结束</th><td>${safe(order?.jobOrderPlanEndDate)}</td></tr>
          <tr><th>实际开始</th><td>${safe(order?.jobOrderActualStartDate || '')}</td><th>实际结束</th><td>${safe(order?.jobOrderActualEndDate || '')}</td></tr>
          <tr><th>销售订单号</th><td>${safe(order?.saleOrderNum) || '/'}</td><th>单位</th><td>${safe(order?.uom)}</td></tr>
        </tbody>
      </table>
    `;

    // 工序信息（若只传入一个process，则只渲染该块）
    const processes: any[] = Array.isArray(order?.jobOrderProcesses) ? order.jobOrderProcesses : [];
    const procBlocks = processes.map((p: any) => {
      const userNames = Array.isArray(p?.users) ? p.users.map((u: any) => u?.name).filter(Boolean).join('、') : '';
      return `
        <div class="process-block">
          <div class="process-head">
            <div class="item"><b>工序序号：</b>${safe(p?.processNumber)}</div>
            <div class="item"><b>工序编码：</b>${safe(p?.processNum)}</div>
            <div class="item"><b>工序名称：</b>${safe(p?.processName)}</div>
            <div class="item"><b>计划产量：</b>${safe(p?.productionQuantity)}</div>
            <div class="item"><b>标准工时：</b>${p?.standardWorkingHours != null ? to2(p?.standardWorkingHours) : ''} ${safe(p?.workingHoursUnit)}</div>
            <div class="item"><b>计划开工：</b>${safe(this.fmtDateStr(p?.planStartTime, true))}</div>
            <div class="item"><b>计划完工：</b>${safe(this.fmtDateStr(p?.planFinishTime, true))}</div>
            <div class="item"><b>分配人员：</b>${userNames}</div>
            <div class="item"><b>派工状态：</b>${p?.isAssign ? '已派工' : '未派工'}</div>
            <div class="item"><b>领料状态：</b>${p?.isIssue ? '已领料' : '未领料'}</div>
            <div class="item"><b>报工合格数：</b>${p?.qualifiedAmount != null ? to2(p?.qualifiedAmount) : ''}</div>
            <div class="item"><b>已报工：</b>${p?.reportedAmount != null ? to2(p?.reportedAmount) : ''}</div>
          </div>
        </div>
      `;
    }).join('');

    const processSection = `
      <div class="sub-title">工序信息</div>
      ${processes.length ? procBlocks : '<div class="muted">无工序</div>'}
    `;

    const html = `
      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>${title}</title>
          ${style}
        </head>
        <body>
          <div class="sheet">
            <div class="header">
              <div class="title">${title}</div>
              <div class="meta">打印时间：${now}</div>
            </div>
            ${headTable}
            ${processSection}
            <div class="footer">
              <div class="cell">制单人：</div>
              <div class="cell">制单时间：</div>
              <div class="cell">审核人：</div>
              <div class="cell">审核时间：</div>
            </div>
          </div>
        </body>
      </html>`;
    return html;
  }
}
